"""
---------------------------------------------------------------------
- File: dynamic_model.py
- Date: 2025/8/9
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 动态生成Pydantic 模型
---------------------------------------------------------------------
"""

from typing import Type, Set

# pydantic
from pydantic import BaseModel, create_model


# 工厂函数，用户动态生成Pydantic 模型
def create_pydantic_model(
    name: str,
    base_model: Type[BaseModel],
    include: Set[str] = None,
    exclude: Set[str] = None,
):
    """
    根据基准模型动态创建一个新的Pydantic模型
    :param name: 模型名称
    :param base_model: 源Pydantic 模型
    :param include: 需要包含的字段集合
    :param exclude: 需要排除的字段集合
    :return: 动态创建一个Pydantic 模型类
    """
    # 复制所有字段
    all_fields = base_model.model_fields.copy()

    # 过滤字段
    if include:
        fields_to_use = {k: v for k, v in all_fields.items() if k in include}
    elif exclude:
        fields_to_use = {k: v for k, v in all_fields.items() if k not in exclude}
    else:
        fields_to_use = all_fields

    # 构建数据
    model_kwargs = {
        field_name: (field_info.annotation, field_info)
        for field_name, field_info in fields_to_use.items()
    }

    # 动态生成
    dynamic_model = create_model(name, __base__=(BaseModel,), **model_kwargs)
    dynamic_model.model_config.update(base_model.model_config)

    return dynamic_model
